/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-02-25 20:42:06
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:00:37
 * @调整预算
 */

'use strict';
define([
    '../../../../../modules/business/videoManage/base/baseView',
    '../../../../../modules/business/pricecalc',
    '../../../../framework/bean/admanage',
    'text!../../tpl/monitor/table/adjustPrice.html'
], function(
    BaseView,
    pricecalc,
    admanageModel,
    tpl
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;
        this.init = function(id, callback) {
            self.id = id;
            self.callback = callback;
            self.render();
        }

        this.render = function() {
            if (!$('#editAdPanel')[0]) {
                $('body').append('<div id="editAdPanel"></div>');
            }
            self.$el = $('#editAdPanel');
            var params = {
                adSet_id: self.id
            }
            admanageModel.getAdSet(params, function(result) {
                var _editAdsetSidepanel = self.$el.sidepanel({
                    saveBtn: I18N.getText('management', 'saveAndClose'),
                    cancelBtn: I18N.getText('management', 'cancel'),
                    title: I18N.getText('management', 'adjustBudgetPrice'),
                    content: I18N.parse(tpl, window.pageName),
                    callback: self.updateCallback
                });

                var objective = result.adSet && result.adSet.campaign && result.adSet.campaign.objective ? result.adSet.campaign.objective : '';
                //if ('' == objective || (objective != 'MOBILE_APP_INSTALLS' && objective != 'WEBSITE_CLICKS')) {
                //    $(_editAdsetSidepanel).find(".panel-body").html(I18N.getText('management', 'editAdDisable')).addClass("disable-edit");
                //    $(_editAdsetSidepanel).find(".btn-primary").addClass("hide");
                //    return;
                //}

                self.objective = objective;
                self.adSet = result.adSet;
                self.targeting_spec = result.targeting_spec;
                self.event();
                result.adSet.promoted_object = JSON.parse(result.adSet.promoted_object); //把属性的类型从String 转成JSON
                self.initRender(result);
            })
        };



        this.event = function() {
            var self = this;
            //预算出价
            self.bindBidEvent();
        }

        this.bindBidEvent = function() {
            var self = this;
            //自动出价与否相关事件
            $('input[name="autobid"]').off("change").on("change", function() {
                if ($(this).val() == 0) {
                    //自动
                    $(".bidamount").addClass("hide").removeClass("error").removeClass("warning");
                    $(".bidamount-reminder").html("");
                    $(".bidamount").find("input").val('');
                    $(".budget").find("input").trigger("keyup");

                    //自动出价只能是标准
                    $('input[name="pacing_type"][value="standard"]').prop("checked", true);
                    $('input[name="pacing_type"][value="no_pacing"]').attr("disabled", "disabled");
                } else {
                    $(".bidamount").removeClass("hide");
                    $('input[name="pacing_type"][value="no_pacing"]').removeAttr("disabled");
                }
            });

            //预算
            $(".edit-ad-container").off('keyup', '.budget>input').on('keyup', '.budget>input', function(e) {
                if ($(this).val() == '') {
                    $(".budget-reminder").html("").addClass("hide");
                    $(this).parent().removeClass("error")
                    return;
                }

                var info = {
                    billing_event: $("div.ndp-drop-wrapper[name=billing_event]").data("val")
                }

                // 1. 当优化方式是-链接点击量,收费方式是-链接点击量,需要进行验证

                //优化方式
                var cOptimizationGoal = $("div.ndp-drop-wrapper[name=optimization_goal]").data("val");
                //收费方式
                var cBillingEvent = $("div.ndp-drop-wrapper[name=billing_event]").data("val");
                if ((cOptimizationGoal == cBillingEvent) && (cOptimizationGoal == 'LINK_CLICKS')) {
                    var warning = self.kit.validateBudget(info, $(".bidamount").find("input").val(),
                        $(this).val(),
                        $(".budget_type").data("val"),
                        self.adSet.start_utc_time, self.adSet.end_utc_time);

                    if (warning) {
                        $(".budget-reminder").html(warning).removeClass("hide");
                        $(this).parent().addClass("error")
                    }
                } else {
                    $(".budget-reminder").html("").addClass("hide");
                    $(this).parent().removeClass("error");
                }
            });

            //单价
            $(".edit-ad-container").off('keyup', '.bidamount>input').on('keyup', '.bidamount>input', function(e) {
                //修改单价，预算需要重新校验
                $(".budget").find("input").trigger("keyup");
                // 1. 当优化方式是-链接点击量,收费方式是-链接点击量,需要进行验证

                //优化方式
                var cOptimizationGoal = $("div.ndp-drop-wrapper[name=optimization_goal]").data("val");
                //收费方式
                var cBillingEvent = $("div.ndp-drop-wrapper[name=billing_event]").data("val");
                if ((cOptimizationGoal == cBillingEvent) && (cOptimizationGoal == 'LINK_CLICKS')) {
                    var _validateReault = self.kit.validateBidAmount($(this).val(), $(this).attr("min"), $(this).attr("max"));
                    if (!_validateReault) {
                        $(".bidamount-reminder").html("");
                        $(this).parent().removeClass("error").removeClass("warning");
                    } else {
                        $(".bidamount-reminder").html(_validateReault.msg);
                        if (_validateReault.type == "error") {
                            $(this).parent().addClass("error").removeClass("warning");
                            $(".bidamount-reminder").addClass("bid-error").removeClass("bid-warning");
                        }
                    }
                } else {
                    $(this).parent().addClass("warning").removeClass("error");
                    $(".bidamount-reminder").addClass("bid-warning").removeClass("bid-error");
                }
            });
        }

        /**
         * { 设置地区 }
         *
         * @method     renderLocations
         */
        this.renderLocations = function() {
            var targeting = self.targeting_spec;
            var names = [];
            self._.each(targeting.geo_locations.countries, function(v) {
                names.push(v.name);
            });
            self._.each(self._.values(targeting.geo_locations), function(t) {
                if (self._.isArray(t)) {
                    self._.each(t, function(i) {
                        if (self._.isString(i.country)) {
                            names.push(i.country)
                        }
                    })
                }
            });
            names = _.uniq(names, true);
            self.$el.find('.bid.area').html(names.join(' , '));
        }

        this.updateCallback = function($elem) {
            if ($(".panel-footer").find(".btn-primary").hasClass("disabled")) {
                console.log("暂不能保存");
                return;
            }
            //对预算和出价的校验
            if ($(".budget").hasClass("error") || $(".budget").find("input").val() == '') {
                $(".budget").find("input").focus();
                return;
            }
            if ($(".bidamount").hasClass("error") || ($('input[name="autobid"]:checked').val() == '1' && $(".bidamount").find("input").val() == '')) {
                $(".bidamount").find("input").focus();
                return;
            }

            var _updateValue = {}

            //优化方向
            var cOptimizationGoal = $("div.ndp-drop-wrapper[name=optimization_goal]").data("val");
            if (self.adSet.optimization_goal != cOptimizationGoal) {
                _updateValue.optimization_goal = cOptimizationGoal;
            }
            _updateValue.custom_event_type = self.adSet.promoted_object.custom_event_type;

            //支付方式
            var cBillingEvent = $("div.ndp-drop-wrapper[name=billing_event]").data("val");
            if (self.adSet.billing_event != cBillingEvent) {
                _updateValue.billing_event = cBillingEvent;
            }

            //预算
            var oldBudget = self.adSet.lifetime_budget && self.adSet.lifetime_budget > 0 ? {
                type: 'lifetime_budget',
                budget: self.adSet.lifetime_budget
            } : {
                type: 'daily_budget',
                budget: self.adSet.daily_budget
            };
            var newBudget = {
                type: $("div.ndp-drop-wrapper[name=budget_type]").data("val"),
                budget: Number(Number($(".budget").find("input").val()) * 100).toFixed(0)
            };

            if (newBudget.type != oldBudget.type || newBudget.budget != oldBudget.budget) {
                if (newBudget.type == 'lifetime_budget') {
                    _updateValue.lifetime_budget = newBudget.budget;
                    _updateValue.daily_budget = 0;
                } else {
                    _updateValue.daily_budget = newBudget.budget;
                    _updateValue.lifetime_budget = 0;
                }
            }

            //自动出价与否
            var cIsAutobid = $('input[name="autobid"]:checked').val() == '0' ? true : false;
            _updateValue.is_autobid = self.adSet.is_autobid;
            if ((!self.adSet.is_autobid && cIsAutobid) || (self.adSet.is_autobid && !cIsAutobid)) {
                _updateValue.is_autobid = cIsAutobid;
            }

            //单价  出价
            var cbid_amount = isNaN(Number($(".bidamount").find("input").val())) ? 0 : Number(Number($(".bidamount").find("input").val()) * 100).toFixed(0);
            //每次都把出价带上,注释掉这一段
            // if ((!self.adSet.bid_amount && cbid_amount) || (self.adSet.bid_amount && !cbid_amount) || (cbid_amount != self.adSet.bid_amount)) {
            _updateValue.bid_amount = cbid_amount;
            // }

            //如果是自动出价,删除 _updateValue.bid_amount
            if (_updateValue.is_autobid && _updateValue.bid_amount) {
                delete _updateValue.bid_amount;
            }

            //投放类型 pacing_type
            var cPacing_type = $('input[name="pacing_type"]:checked').val();
            var oldPacing_type = self.adSet.pacing_type ? JSON.parse(self.adSet.pacing_type) : [];
            if (oldPacing_type.indexOf(cPacing_type) == -1) {
                if (cPacing_type == 'standard') {
                    var _i = oldPacing_type.indexOf('no_pacing');
                    if (_i > -1) {
                        oldPacing_type.splice(_i, 1);
                    }
                } else {
                    var _i = oldPacing_type.indexOf('standard');
                    if (_i > -1) {
                        oldPacing_type.splice(_i, 1);
                    }
                }

                oldPacing_type.push(cPacing_type);
                _updateValue.pacing_type = oldPacing_type;
            }

            console.log(_updateValue);
            console.log(self.kit.isEmptyObject(_updateValue));
            if (self.kit.isEmptyObject(_updateValue)) {
                $elem.sidepanel('hide');
                console.log("未做任何修改")
                return;
            }

            var par = {
                "adSet_id": self.adSet.adset_id,
                // 广告ID（必须项）
                "job_type": "update_ad_set",
                //更新操作类型,
                "value": _updateValue
            };

            admanageModel.updateAdSet(par, function(result) {
                self.callback(result, 1, self.queryStatusOK, self.queryStatusFail); //调用 table.js queryStatus
            });
        }

        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusOK
         * @param      {<type>}  result  { description }
         */
        this.queryStatusOK = function(result) {
            console.info(result)
            self.$el.sidepanel('hide');
        }

        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusFail
         * @param      {<type>}  result  { description }
         */
        this.queryStatusFail = function(result) {
            console.info(result)
        }

        this.initRender = function(_result) {
            var self = this;
            //渲染出价
            self.renderBid(_result.adSet, _result.condition);
            self.renderLocations();
        }

        function bidAmountLimit(_condition) {
            var _bidAmountRange = self.kit.bidAmountRange({
                optimization_goal: $("div.ndp-drop-wrapper[name=optimization_goal]").data("val"),
                billing_event: $("div.ndp-drop-wrapper[name=billing_event]").data("val")
            }, _condition ? _condition.priceLimit : undefined)
            var _bidamountPlaceholder;
            if (_bidAmountRange.max){
                _bidamountPlaceholder = I18N.getText('createAd', 'moneyRange',_bidAmountRange.min,_bidAmountRange.max);
            } else {
                _bidamountPlaceholder = I18N.getText('createAd', 'moneyRangeNoMax',_bidAmountRange.min);
            }
            return {
                bidamountPlaceholder: _bidamountPlaceholder,
                min: _bidAmountRange.min,
                max: _bidAmountRange.max
            };
        }


        this.renderBid = function(_adset, _condition) {
            var self = this;
            //排期
            var _startTimeShow = moment(_adset.start_utc_time).utcOffset(window.sessionStorage.timezoneValue).format('YYYY-MM-DD HH:mm');
            var _endTimeShow = ''
            if (_adset.end_utc_time) {
                _endTimeShow = moment(_adset.end_utc_time).utcOffset(window.sessionStorage.timezoneValue).format('YYYY-MM-DD HH:mm');
            } else {
                _endTimeShow = I18N.getText('createAd', 'continuously');
            }
            $(".schedule").html(_startTimeShow + ' ~ ' + _endTimeShow);


            var _optimizationGoals = [];
            if (self.objective == 'MOBILE_APP_INSTALLS') { //应用安装
                _optimizationGoals = self.bidInfo.app;
            } else if (self.objective == 'WEBSITE_CLICKS') { //外链
                _optimizationGoals = self.bidInfo.outlink;
            } else if (self.objective == 'CONVERSIONS') { //CONVERSIONS
                _optimizationGoals = self.bidInfo.dpa;
            } else if (self.objective == 'PRODUCT_CATALOG_SALES') { //DPA CONVERSIONS ? PRODUCT_CATALOG_SALES
                _optimizationGoals = self.bidInfo.dpa;
            } else {
                //console.error("unsupported objective!")
                console.log("unsupported objective!");
            }

            //optimization_goal
            var _optimizationGoalE = $("div.ndp-drop-wrapper[name=optimization_goal]").empty().drop({
                data: _optimizationGoals,
                caret: "glyphicon-menu-right"
            }).on("ITEM_CHANGE", function(e) {
                //优化方向与收费方式联动
                var _sOptimizationGoal = e.originalEvent.data.val;
                var _index = self.kit.keyIn(_optimizationGoals, _sOptimizationGoal, 'id');
                if (_index > -1) {
                    var nB;
                    if (_sOptimizationGoal == 'APP_INSTALLS' && !self.cpaSupport)
                        nB = _optimizationGoals[_index].billingEventsNotSupportCpa;
                    else
                        nB = _optimizationGoals[_index].billingEvents;

                    //只有是OFFSITE_CONVERSIONS 时，活动类型才显示
                    if (_sOptimizationGoal == 'OFFSITE_CONVERSIONS') {
                        $("div.bid-area .custom_event_type").show();
                    } else {
                        $("div.bid-area .custom_event_type").hide();
                    }
                    $("div.ndp-drop-wrapper[name=billing_event]").empty().drop({
                        data: nB,
                        caret: "glyphicon-menu-right"
                    }).val(nB[0]);
                }
                //随着优化方向的变动，出价提示也会变更
                var _bidamountLimit = bidAmountLimit(_condition);
                $(".bidamount").find("input").attr("placeholder", _bidamountLimit.bidamountPlaceholder).attr("min", _bidamountLimit.min).attr("max", _bidamountLimit.max);
                $(".edit-ad-container").find('.bidamount>input').trigger('keyup');
            });



            var dbpBidInfo = _.findWhere(self.bidInfo.dpa, {
                id: "OFFSITE_CONVERSIONS"
            });

            //活动类型事件
            $("div.ndp-drop-wrapper[name=custom_event_type]").empty().drop({
                data: dbpBidInfo.customEventType,
                caret: "glyphicon-menu-right"
            }).on("ITEM_CHANGE", function(e) {
                _adset.promoted_object.custom_event_type = e.originalEvent.data.val;
            }).val(_.findWhere(dbpBidInfo.customEventType, {
                "id": _adset.promoted_object.custom_event_type
            }));

            var _ioG = self.kit.findBykey(_optimizationGoals, _adset.optimization_goal, 'id');
            _optimizationGoalE.val(_ioG)

            var initNB;
            if (_adset.optimization_goal == 'APP_INSTALLS' && !self.cpaSupport) {
                initNB = _ioG.billingEventsNotSupportCpa;
            } else {
                initNB = _ioG.billingEvents;
            }
            if (_adset.optimization_goal == 'OFFSITE_CONVERSIONS') {
                $("div.bid-area .custom_event_type").show();
            } else {
                $("div.bid-area .custom_event_type").hide();
            }
            //billing_event
            $("div.ndp-drop-wrapper[name=billing_event]").empty().drop({
                data: initNB,
                caret: "glyphicon-menu-right"
            }).on("ITEM_CHANGE", function(e) {
                //随着出价方式的变动，出价提示也会变更
                var _bidamountLimit = bidAmountLimit(_condition);
                $(".bidamount").find("input").attr("placeholder", _bidamountLimit.bidamountPlaceholder).attr("min", _bidamountLimit.min).attr("max", _bidamountLimit.max);
                $(".edit-ad-container").find('.bidamount>input').trigger('keyup');
            }).val(self.kit.findBykey(_ioG.billingEvents, _adset.billing_event, 'id'));

            //budget_type
            var initBudgetType;
            var initBudget;
            if (_adset.daily_budget && _adset.daily_budget > 0) {
                initBudgetType = {
                    id: "daily_budget",
                    text: I18N.getText('createAd', 'dailyBudget'),
                    val: 'daily_budget'
                };
                initBudget = _adset.daily_budget;
            } else {
                initBudgetType = {
                    id: "lifetime_budget",
                    text: I18N.getText('createAd', 'lifetimeBudget'),
                    val: 'lifetime_budget'
                }
                initBudget = _adset.lifetime_budget;
            }

            //设置预算
            $("div.ndp-drop-wrapper[name=budget_type]").drop({
                data: [{
                    id: "daily_budget",
                    text: I18N.getText('createAd', 'dailyBudget'),
                    val: 'daily_budget'
                }, {
                    id: "lifetime_budget",
                    text: I18N.getText('createAd', 'lifetimeBudget'),
                    val: 'lifetime_budget',
                    disable: _adset.end_utc_time ? false : true
                }],
                caret: "glyphicon-menu-right"
            }).on("ITEM_CHANGE", function(e) {
                $(".edit-ad-container").find('.budget>input').trigger('keyup');
            }).val(initBudgetType);

            $("div.ndp-sinput-wrapper[name=budget]").sinput({
                xion: "<span>$</span>",
                placeholder: I18N.getText('createAd', 'pleaseInputBudget'),
                pos: "left", //图标显示在左边  “left”, "right"
                default: Number(initBudget / 100).toFixed(2)
            });
            //预算精确到小数点两位
            $(".budget").find("input").numeral({
                'scale': 2
            });

            //单价
            var _bidamountLimit = bidAmountLimit(_condition);
            var _bidamountE = $("div.ndp-sinput-wrapper[name=bidamount]").sinput({
                xion: "<span>$</span>",
                placeholder: _bidamountLimit.bidamountPlaceholder,
                pos: "left" //图标显示在左边  “left”, "right"
            });
            $("div.ndp-sinput-wrapper[name=bidamount]").find("input").attr("min", _bidamountLimit.min).attr("max", _bidamountLimit.max);
            var _initBid = '';
            if (_adset.is_autobid && _adset.is_autobid == true) {
                $('input[name="autobid"][value="0"]').prop("checked", true).trigger("change");
            } else {
                $('input[name="autobid"][value="1"]').prop("checked", true).trigger("change");
                _initBid = Number(_adset.bid_amount / 100).toFixed(2);
            }
            _bidamountE.val(_initBid);
            //单价精确到小数点两位
            $(".bidamount").find("input").numeral({
                'scale': 2
            });
            //pacing_type
            var _initPacingType;
            if (!_adset.pacing_type || _adset.pacing_type.length == 0 || _adset.pacing_type.indexOf("standard") > -1) {
                //标准
                _initPacingType = "standard";
            } else {
                //加速
                _initPacingType = "no_pacing";
            }
            $('input[name="pacing_type"][value="' + _initPacingType + '"]').prop("checked", true);

        }



        /**
         * 字典
         */
        this.bidInfo = {
            "outlink": [{
                id: "LINK_CLICKS",
                text: I18N.getText('createAd', 'websiteLinkClicks'),
                val: "LINK_CLICKS",
                billingEvents: [{
                    id: "LINK_CLICKS",
                    text: I18N.getText('createAd', 'linkClicks'),
                    val: "LINK_CLICKS"
                }, {
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }]
            }, {
                id: "IMPRESSIONS",
                text: I18N.getText('createAd', 'impressions'),
                val: "IMPRESSIONS",
                billingEvents: [{
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }]
            }, {
                id: "REACH",
                text: I18N.getText('createAd', 'dailyUniqueReach'),
                val: "REACH",
                billingEvents: [{
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }]
            }],
            "app": [{
                id: "APP_INSTALLS",
                text: I18N.getText('createAd', 'appInstalls'),
                val: "APP_INSTALLS",
                billingEvents: [{
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }, {
                    id: "APP_INSTALLS",
                    text: I18N.getText('createAd', 'appInstalls'),
                    val: "APP_INSTALLS"
                }],
                billingEventsNotSupportCpa: [{
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }, {
                    id: "APP_INSTALLS",
                    text: (I18N.getText('createAd', 'appInstalls') + I18N.getText('createAd', 'appInstallsNoPermission')),
                    val: "APP_INSTALLS",
                    disable: true
                }]
            }, {
                id: "LINK_CLICKS",
                text: I18N.getText('createAd', 'linkClicks'),
                val: "LINK_CLICKS",
                billingEvents: [{
                    id: "LINK_CLICKS",
                    text: I18N.getText('createAd', 'linkClicks'),
                    val: "LINK_CLICKS"
                }, {
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }]
            }],
            "dpa": [{
                id: "OFFSITE_CONVERSIONS",
                text: I18N.getText('createAd', 'offsiteConversions'),
                val: "OFFSITE_CONVERSIONS",
                billingEvents: [{
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }, ],
                billingEventsNotSupportCpa: [{
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }, ],
                customEventType: [{
                    id: "PURCHASE",
                    text: I18N.getText('createAd', 'purchase'),
                    val: "PURCHASE"
                }, {
                    id: "ADD_TO_CART",
                    text: I18N.getText('createAd', 'addToCart'),
                    val: "ADD_TO_CART"
                }]
            }, {
                id: "LINK_CLICKS",
                text: I18N.getText('createAd', 'linkClicks'),
                val: "LINK_CLICKS",
                billingEvents: [{
                    id: "LINK_CLICKS",
                    text: I18N.getText('createAd', 'linkClicks'),
                    val: "LINK_CLICKS"
                }, {
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }]
            }, {
                id: "IMPRESSIONS",
                text: I18N.getText('createAd', 'impressions'),
                val: "IMPRESSIONS",
                billingEvents: [{
                    id: "IMPRESSIONS",
                    text: I18N.getText('createAd', 'impressions'),
                    val: "IMPRESSIONS"
                }]
            }]
        }

    };
    return me;
});
